'use strict';
const FtpSrv = require('ftp-srv');
const bunyan = require('bunyan');
const fs = require('fs');
const path = require('path');

const host = '0.0.0.0';
const port = 21;
const user = 'RZFIBER';
const pass = 'RZFIBER';
const pasv_url = '0.0.0.0';
const pasv_range_min = 8400;
const pasv_range_max = 8500;

const startFtpServer = async (host, port, user, pass) => {
  const quietLog = bunyan.createLogger({
    name: 'quiet-logger',
    level: 60,
  });

  const server = new FtpSrv({
    log: quietLog,
    url: `ftp://${host}:${port}`,
    pasv_url,
    pasv_min: pasv_range_min,
    pasv_max: pasv_range_max,
  });


  server.on('login', async ({ connection, username, password }, resolve, reject) => {

    const destinyFolder = path.join(__dirname, 'homedir');
    if (username === user && password === pass) {
      // If connected, add a handler to confirm file uploads
      connection.on('STOR', (error, fileName) => {
        if (error) {
          const errMessage = `FTP server error: could not receive file ${fileName} for upload ${error}`;
          console.error(errMessage);
        }
        console.info(`FTP server: upload successfully received - ${fileName}`);
      });

      connection.on('DELE', (error, fileName) => {
        if (error) {
          const errMessage = `FTP server error: can't delete ${fileName} for upload ${error}`;
          console.error(errMessage);
        }
      });

      resolve({
        root: destinyFolder,
        // blacklist: ['RMD', 'RNFR', 'RNTO', 'DELE']
      });
    } else {
      const error = new Error('Unable to authenticate with FTP server: bad username or password');
      reject(error);
    }
  });

  server.on('client-error', ({ context, error }) => {
    console.error(`FTP server error: error interfacing with client ${context} ${error} on ftp://${host}:${port} ${JSON.stringify(error)}`);
  });

  const closeFtpServer = async () => {
    await server.close();
  };

  // The types are incorrect here - listen returns a promise
  await server.listen().then(() => {
    console.log(`ftp server ready at ftp://localhost:${port}`);
  });

  return {
    shutdownFunc: async () => {
      // server.close() returns a promise - another incorrect type
      await closeFtpServer();
    },
  };
};


const ftpsrv = startFtpServer(host, port, user, pass);
module.exports = ftpsrv;
